package org.example.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.micrometer.common.util.StringUtils;
import org.example.entity.Dictionaries;
import org.example.mapper.DictionariesMapper;
import org.example.service.DictionariesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author wxm
 * @date 2025/3/3 14:55
 */
@Service
public class DictionariesServiceImpl extends ServiceImpl<DictionariesMapper, Dictionaries> implements DictionariesService {
    @Autowired
    private DictionariesMapper dictionariesMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${redisData.timeout}")
    private Integer redisDataTimeout;

    @Override
    public List<String> getColumnType(String parentColumn) {
        String redisData = redisTemplate.opsForValue().get(parentColumn);
        List<String> tableNameList;
        if (StringUtils.isEmpty(redisData)) {
            synchronized (this) {
                redisData = redisTemplate.opsForValue().get(parentColumn);
                if (StringUtils.isEmpty(redisData)) {
                    tableNameList = dictionariesMapper.selectDataByParent(parentColumn);
                    Collections.sort(tableNameList);
                    redisTemplate.opsForValue().set(parentColumn, JSONObject.toJSONString(tableNameList), redisDataTimeout, TimeUnit.SECONDS);
                } else {
                    tableNameList = parseRedisData(redisData);
                }
            }
        } else {
            tableNameList = parseRedisData(redisData);
        }
        return tableNameList;
    }

    @Override
    public List<String> selectAllParent() {
        return dictionariesMapper.selectAllParent().stream().distinct().collect(Collectors.toList());
    }

    @Override
    public void insertParent(String parentName) {
        dictionariesMapper.insertParent(parentName);
    }

    @Override
    public void insertSon(String parentName, String sonName) {
        dictionariesMapper.insertSon(parentName,sonName);
    }

    private List<String> parseRedisData(String redisData) {
        try {
            JSONArray jsonArray = JSONArray.parseArray(redisData);
            return jsonArray.toJavaList(String.class);
        } catch (Exception e) {
            log.error("Error parsing Redis data: " + redisData, e);
            return Collections.emptyList();
        }
    }
}
